package com.spn.blog.common.dao.pojo;

import com.alibaba.fastjson.annotation.JSONField;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.spn.blog.common.config.MyGrantedAuthority;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

@NoArgsConstructor
@AllArgsConstructor
@Data
public class LoginUser implements UserDetails {
    private static final long serialVersionUID = 1L;

    private SysUser sysUser;

    private List<String> permissions;

    @JSONField(serialize = false)
    List<MyGrantedAuthority> authorities; // 这个权限变量太多，进入redis也影响效率，这里就把他设置为不进行序列化

    public LoginUser(SysUser sysUser, List<String> permissions) {
        this.sysUser = sysUser;
        this.permissions = permissions;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        // 这里if优化，因为每次过滤器都会走下面这个stream，浪费效率。
        if (authorities != null) {
            return authorities;
        }
        authorities = permissions.stream().map(MyGrantedAuthority::new).collect(Collectors.toList());
        // 在流通道里面，每次map遍历，都new一个SimpleGrantedAuthority对象，然后给他收集到list里面，最后返回list。
        return authorities;
         }

    @Override
    public String getPassword() {
        return sysUser.getPassword();
    }

    @Override
    public String getUsername() {
        return sysUser.getAccount();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}